import React from 'react'
import {
  Checkbox, Input, Popconfirm, Select, Tooltip,
} from 'antd'
import lodash from 'lodash'
import { SettingOutlined } from '@ant-design/icons'
import {
  ProTableOptions,
} from '@/components'
import { paramDataTypeArr, paramOperatorArr } from '@/utils/constans'
import { requestIdMap, responseIdMap } from '@/utils/utils'

const { Option } = Select
const { cloneDeep } = lodash

export function normalOnChange(theKey, originDataKey, index) {
  // 特定数据结构下通用的：change事件去往 setState 的function
  return (e) => {
    // 利用getRealIndexByType 方法获取 index标识下，originDataKey为特征值的数据集合
    const realIndexByType = getRealIndexByType.call(this, originDataKey)
    // 得到state的key+realIndex+克隆的数据集
    const { key, realIndex, theParamsCopy } = realIndexByType
    // 再利用事件e 的nativeEvent 来区分是否为输入框/多行输入框
    if (e instanceof Object && (e.nativeEvent.type === 'input' || e.nativeEvent.type === 'textarea')) {
      theParamsCopy[realIndex + index][theKey] = e?.target?.value || ''
    } else {
      theParamsCopy[realIndex + index][theKey] = e
    }
    // 把新的state值设置回去
    this.setState({
      [key]: theParamsCopy,
    })
  }
}

export function inputNormalRender(key, width = 128, originDataKey = 'response') {
  // 特定数据结构下通用的：Input输入框dom，同时使用normalOnChange 作为onChange 方法
  return (text, record, index) => <Input
    maxLength={width}
    value={text}
    placeholder="请输入"
    onChange={normalOnChange.call(this, key, originDataKey, index)}
  />
}

export function getRealIndexByType(type) {
  // 特定数据结构下通用的：使用 originDataKey等参数为type，返回表格Ref检索后的realIndex+state关键key字符串+已克隆的state关键Key的值
  const key = `${type}Params`
  const theParams = this.state[key]
  const theParamsCopy = cloneDeep(theParams)
  const ref = this[`${key.slice(0, 3)}TableRef`]
  const { pageNum, pageSize } = ref?.current?.state || {}
  const realIndex = (pageNum - 1) * pageSize
  return { key, realIndex, theParamsCopy }
}

export function selectedApiTypeToColumn() {
  // 根据从指向的this的state中取出特定的数据结构
  // 依据特定的数据结构完成 特定的column输出
  // 区分了向导模式/脚本模式 + 请求参数/返回参数+指标API/脚本API
  return (type = 'response') => {
    const {
      selectedApiType,
      requestParams,
    } = this.state
    // 绑定字段
    const bindColumnName = {
      title: '绑定字段',
      dataIndex: 'bindColumnName',
    }
    console.log(requestParams)
    const requestParamsFn = () => {
      for (let i = 0; i < requestParams.length; i++) {
        if (!requestParams[i].paramRequire) {
          return false
        }
      }
      if (requestParams.length) {
        return true
      }
      return false
    }
    // 绑定字段 返回参数部分1
    const req_param_columns_1 = [
      {
        title: (
          <span>
            操作符
            <Tooltip
              placement="top"
              title={
                <div>
                  <p>操作符BETWEEN的传参方式为：aaa,bbb</p>
                </div>
              }
            >
              <i style={{ color: 'rgb(0, 132, 255)' }} className="iconfont icon-yiwentishi" />
            </Tooltip>
            &nbsp;
            <Tooltip
              placement="top"
              title={
                <div>
                  <p>进行操作符的整体操作</p>
                </div>
              }
            >
              <SettingOutlined
                style={{ color: 'rgb(0, 132, 255)' }}
                onClick={() => {
                  // 已预设的visible
                  this.setState({ paramsSetModalVisible: true })
                }}
              />
            </Tooltip>
          </span>
        ),
        dataIndex: 'paramOperator',
        width: '10%',
        render: (text, record, index) => (
          <Select
            placeholder="全部"
            value={text}
            onChange={normalOnChange.call(this, 'paramOperator', 'request', index)}
          >
            {paramOperatorArr.map((val, keyParamIndex) => (
              <Option key={`paramOperatorArr${keyParamIndex}`} value={keyParamIndex}>
                {val}
              </Option>
            ))}
          </Select>
        ),
      },
    ]
    // 绑定字段 返回参数部分2
    const req_param_columns_2 = [
      {
        title: (
          <span>是否必填<Checkbox
            checked={requestParamsFn()}
            onChange={(e) => {
              if (e.target.checked) {
                requestParams.map((item) => {
                  item.paramRequire = 1
                })
              } else {
                requestParams.map((item) => {
                  item.paramRequire = 0
                })
              }
              this.setState({
                requestParams: [...requestParams],
              })
            }}
          /></span>
        ),
        width: '8%',
        dataIndex: 'paramRequire',
        render: (text, record, index) => (
          <Checkbox
            checked={text === 1}
            onChange={(e) => normalOnChange.call(this, 'paramRequire', type, index)(e.target.checked ? 1 : 0)}
          />
        ),
      },
      {
        title: '默认值',
        dataIndex: 'defaultValue',
        render: inputNormalRender.call(this, 'defaultValue', 128, type),
      },
    ]
    // 判断向导模式 or 脚本模式
    const bolSelectedApiType = selectedApiType === '0' || selectedApiType === 0
    return [{
      title: '参数名称',
      dataIndex: 'paramName',
      render: inputNormalRender.call(this, 'paramName', 256, type),
    },
      ...(bolSelectedApiType ? [bindColumnName]
        : (type === 'response' && [{
          ...bindColumnName,
          render: inputNormalRender.call(this, 'bindColumnName'),
        }] || [])),
      ...(type === 'response' ? [] : req_param_columns_1),
      {
        title: '参数类型',
        dataIndex: 'paramDataType',
        render: (text, record, index) => (
          <Select
            placeholder="全部"
            value={text}
            onChange={normalOnChange.call(this, 'paramDataType', type, index)}
          >
            {paramDataTypeArr.map((val, keyParams) => (
              <Option key={keyParams} value={val}>
                {val}
              </Option>
            ))}
          </Select>
        ),
      },
      ...(type === 'response' ? [] : req_param_columns_2),
      {
        title: '示例值',
        dataIndex: 'exampleValue',
        render: inputNormalRender.call(this, 'exampleValue', 128, type),
      },
      {
        title: '描述',
        dataIndex: 'paramDesc',
        render: inputNormalRender.call(this, 'paramDesc', 256, type),
      },
      ...(!bolSelectedApiType ? [
        {
          title: '操作',
          dataIndex: 'action',
          width: '48px',
          render: (text, record, index) => (
            <ProTableOptions>
              <Popconfirm
                title="是否删除本条参数?"
                onConfirm={() => {
                  const { key, realIndex, theParamsCopy } = getRealIndexByType.call(this, type)
                  theParamsCopy.splice(realIndex + index, 1)
                  this.setState({
                    [key]: theParamsCopy,
                  })
                }}
                okText="确认"
                cancelText="取消"
              >
                <span>删除</span>
              </Popconfirm>
            </ProTableOptions>
          ),
        }] : []),
    ]
  }
}

export function addNewParamsRow() {
  // 特定数据结构下对于可编辑表格增加一行的按钮点击事件
  return (type) => () => {
    let data
    let mapFn
    switch (type) {
      case 'request': {
        data = {
          paramType: 0,
          paramName: '',
          paramPosition: null,
          bindColumnName: null,
          paramDataType: null,
          paramOperator: null,
          paramRequire: null,
          exampleValue: null,
          defaultValue: null,
          paramDesc: null,
        }
        mapFn = requestIdMap
      }
        break
      case 'response': {
        data = {
          paramType: 1,
          paramName: '',
          paramPosition: null,
          bindColumnName: '',
          paramDataType: null,
          paramOperator: null,
          paramRequire: null,
          exampleValue: null,
          defaultValue: null,
          paramDesc: null,
        }
        mapFn = responseIdMap
      }
        break
    }
    const { key, realIndex, theParamsCopy } = getRealIndexByType.call(this, type)
    if (realIndex > 0) {
      theParamsCopy.splice(realIndex, 0, data)
    } else {
      theParamsCopy.unshift(data)
    }
    this.setState({
      [key]: [...theParamsCopy].map(mapFn),
    })
  }
}
